﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Net;

namespace ink
{

    public partial class UserControl1 : UserControl
    {
        //Ink variables
        private int inkPictureWidthSz = 800;
        private int inkPictureHeightSz = 600;

        private int inkPictureOriginWidthSz = 800;
        private int inkPictureOriginHeightSz = 600;

        private float inkPictureZoomFactor = 1.0f;

        private static Guid guidImage   = new Guid("{1C3F0F7E-9C28-4797-9223-509AEE627A13}");
        private static Guid guidBGColor = new Guid("{1C3F0F7E-9C28-4797-9223-509AEE627A14}");

        //Network variables
        private bool bDispDebugMessage = false;
        private bool bListen = false;

        public UserControl1()
        {

            InitializeComponent();

            //this.inkPicture1.Ink.InkAdded += new Microsoft.Ink.StrokesEventHandler(Ink_InkAdded);
            //this.inkPicture1.Ink.InkDeleted += new Microsoft.Ink.StrokesEventHandler(Ink_InkDeleted);

            this.inkPicture1.Ink.InkAdded +=  new Microsoft.Ink.StrokesEventHandler(Strokes_StrokesAdded);
            this.inkPicture1.Ink.InkDeleted += new Microsoft.Ink.StrokesEventHandler(Strokes_StrokesRemoved);

        }

        private void UserControl1_Load(object sender, EventArgs e)
        {
            resetSz(sender, e);
            setEraseWidth();

            inkPicture1.BackColor = Color.White;

        }

        private void UserControl1_Disposed(object sender, EventArgs e)
        {
            //if (client != null)
            //{
            //    client.Disconnect();
            //    client.Shutdown();

            //    client = null;
            //}

            if (vapi != null)
            {
                vapi.releaseVAST();
                vapi = null;

                System.Threading.Thread.Sleep(2000);
            }
        }

        private void resetSz(object sender, EventArgs e)
        {
            //初始化物件位置
            //初始化物件參數

            //ribbon
            this.ribbonControl1.Location = new System.Drawing.Point(0, 0);

            //panel
            int nY = this.ribbonControl1.Location.Y + this.ribbonControl1.ClientSize.Height;
            this.panel1.Location = new System.Drawing.Point(0, nY);
            this.panel1.Size = new System.Drawing.Size(this.ClientSize.Width, this.ClientSize.Height -nY);

            //inkpicture
            this.inkPicture1.Size = new System.Drawing.Size(inkPictureWidthSz, inkPictureHeightSz);
            this.inkPicture1.Location = new System.Drawing.Point((int)((this.panel1.ClientSize.Width - inkPictureWidthSz) * 0.5), (int)((this.panel1.ClientSize.Height - inkPictureHeightSz) * 0.5));

            //debug message
            this.richTextBox1.Location = new System.Drawing.Point(5, nY+5);
            this.richTextBox1.Size = new System.Drawing.Size(this.ClientSize.Width-10, this.ClientSize.Height - nY-10);
            if (bDispDebugMessage)
            {
                this.richTextBox1.Visible = true;
                this.panel1.Visible = false;
            }
            else
            {
                this.richTextBox1.Visible = false;
                this.panel1.Visible = true;
            }



                //invalide
                this.ribbonControl1.Invalidate();
            this.panel1.Invalidate();
            this.inkPicture1.Invalidate();
            
        }

        private void resetToolsButton(mRibbon.RibbonButton button)
        {
            if (button.IsPressed == false)
            {
                //reset button state
                this.ribbonButton1.IsPressed = false;
                this.ribbonButton2.IsPressed = false;
                this.ribbonButton3.IsPressed = false;

                button.IsPressed = true;

                this.ribbonButton1.Invalidate();
                this.ribbonButton2.Invalidate();
                this.ribbonButton3.Invalidate();
            }
        }

        private void resetColorsButton(mRibbon.RibbonButton button)
        {
            //if (button.IsPressed == false)
            //{
            //    //reset button state
            //    this.ribbonButton5.IsPressed = false;
            //    this.ribbonButton6.IsPressed = false;
            //    this.ribbonButton7.IsPressed = false;
            //    this.ribbonButton8.IsPressed = false;
            //    this.ribbonButton4.IsPressed = false;

            //    button.IsPressed = true;

            //    this.ribbonButton4.Invalidate();
            //    this.ribbonButton5.Invalidate();
            //    this.ribbonButton6.Invalidate();
            //    this.ribbonButton7.Invalidate();
            //    this.ribbonButton8.Invalidate();
            //}

        }

        private void resetSizeButton(mRibbon.RibbonButton button)
        {
            if (button.IsPressed == false)
            {
                //this.ribbonButton9.IsPressed = false;
                this.ribbonButton10.IsPressed = false;
                this.ribbonButton11.IsPressed = false;
                this.ribbonButton12.IsPressed = false;

                button.IsPressed = true;

                //this.ribbonButton9.Invalidate();
                this.ribbonButton10.Invalidate();
                this.ribbonButton11.Invalidate();
                this.ribbonButton12.Invalidate();
            }

        }

        private void setEraseWidth()
        {
            //default
            if (this.ribbonButton12.IsPressed == true)
                this.inkPicture1.EraserWidth = 250;

            //thin
            if (this.ribbonButton11.IsPressed == true)
                this.inkPicture1.EraserWidth = 100;

            //thick
            if (this.ribbonButton10.IsPressed == true)
                this.inkPicture1.EraserWidth = 500;

        }

        //private void button4_Click(object sender, EventArgs e)
        //{
        //    this.inkPicture1.Ink.DeleteStrokes();
        //    this.inkPicture1.Invalidate();
        //}

        //pen
        private void ribbonButton1_Click(object sender, EventArgs e)
        {
            this.inkPicture1.InkEnabled = true;
            this.inkPicture1.EditingMode = Microsoft.Ink.InkOverlayEditingMode.Ink;

            resetToolsButton( this.ribbonButton1 );

        }

        //stroke eraser
        private void ribbonButton2_Click(object sender, EventArgs e)
        {
            this.inkPicture1.InkEnabled = true;
            this.inkPicture1.EraserMode = Microsoft.Ink.InkOverlayEraserMode.StrokeErase;
            this.inkPicture1.EditingMode = Microsoft.Ink.InkOverlayEditingMode.Delete;

            resetToolsButton(this.ribbonButton2);

        }

        //point eraser
        private void ribbonButton3_Click(object sender, EventArgs e)
        {
            this.inkPicture1.InkEnabled = true;
            this.inkPicture1.EraserMode = Microsoft.Ink.InkOverlayEraserMode.PointErase;
            this.inkPicture1.EditingMode = Microsoft.Ink.InkOverlayEditingMode.Delete;

            
            resetToolsButton(this.ribbonButton3);
            setEraseWidth();
        }

        //Color1 (black)
        private void ribbonButton5_Click(object sender, EventArgs e)
        {
            this.inkPicture1.DefaultDrawingAttributes.Color = Color.Black;
            this.resetColorsButton( this.ribbonButton5 );

        }

        //color2 (red)
        private void ribbonButton6_Click(object sender, EventArgs e)
        {
            this.inkPicture1.DefaultDrawingAttributes.Color = Color.Red;
            this.resetColorsButton(this.ribbonButton6);
        }

        //color3 (blue)
        private void ribbonButton7_Click(object sender, EventArgs e)
        {
            this.inkPicture1.DefaultDrawingAttributes.Color = Color.Blue;
            this.resetColorsButton(this.ribbonButton7);

        }

        //color4 (green)
        private void ribbonButton8_Click(object sender, EventArgs e)
        {
            this.inkPicture1.DefaultDrawingAttributes.Color = Color.Green;
            this.resetColorsButton(this.ribbonButton8);
        }

        //defaultsize
        private void ribbonButton12_Click(object sender, EventArgs e)
        {
            this.inkPicture1.DefaultDrawingAttributes.Width = 50;

            
            this.resetSizeButton(this.ribbonButton12);
            setEraseWidth();

        }

        //thin size
        private void ribbonButton11_Click(object sender, EventArgs e)
        {
            this.inkPicture1.DefaultDrawingAttributes.Width = 30;
            
            
            this.resetSizeButton(this.ribbonButton11);
            setEraseWidth();
            
        }

        //thick size
        private void ribbonButton10_Click(object sender, EventArgs e)
        {
            this.inkPicture1.DefaultDrawingAttributes.Width = 150;

            
            this.resetSizeButton(this.ribbonButton10);
            setEraseWidth();
            
        }

        //edit color
        private void ribbonButton4_Click(object sender, EventArgs e)
        {
            ColorDialog colorDlg = new ColorDialog();
            colorDlg.AllowFullOpen = true;
            colorDlg.AnyColor = true;
            colorDlg.SolidColorOnly = false;
            colorDlg.Color = Color.Red;

            if (colorDlg.ShowDialog() == DialogResult.OK)
            {
                this.inkPicture1.DefaultDrawingAttributes.Color = colorDlg.Color;
            }
        }

        public void setupBackgroundImage(Bitmap image)
        {
            this.inkPicture1.SizeMode = PictureBoxSizeMode.StretchImage;
            this.inkPicture1.Image = (Image)image;

            //if (client != null)
            //{
            //    byte[] imgArray;
            //    MemoryStream memStream = new MemoryStream();
            //    BinaryFormatter bf = new BinaryFormatter();
            //    bf.Serialize(memStream, inkPicture1.Image);
            //    imgArray = memStream.GetBuffer();
            //    string strImg = Convert.ToBase64String(imgArray);

            //    client.Send("!ANNOUNCE " + "!imgdata" + strImg);
            //}

            if (vapi != null)
            {
                byte[] imgArray;
                MemoryStream memStream = new MemoryStream();
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(memStream, inkPicture1.Image);
                imgArray = memStream.GetBuffer();
                string strImg = Convert.ToBase64String(imgArray);

                this.richTextBox1.Text += "!imgdata" + strImg + "\n";
                vapi.sndMessage("!imgdata" + strImg);

            }

            this.inkPicture1.Invalidate();
        }

        //background image
        private void ribbonButton19_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Image files (*.bmp; *.gif; *.jpg; *.png)|*.bmp;*.gif;*.jpg;*.png|" + "All files (*.*)|*.*";

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.inkPicture1.SizeMode = PictureBoxSizeMode.StretchImage;
                this.inkPicture1.Image = Image.FromFile(openFileDialog.FileName);

                //if (client != null)
                //{
                //    byte[] imgArray;
                //    MemoryStream memStream = new MemoryStream();
                //    BinaryFormatter bf = new BinaryFormatter();
                //    bf.Serialize(memStream, inkPicture1.Image);
                //    imgArray = memStream.GetBuffer();
                //    string strImg = Convert.ToBase64String(imgArray);

                //    client.Send("!ANNOUNCE " + "!imgdata" + strImg);
                //}

                if (vapi != null)
                {
                    byte[] imgArray;
                    MemoryStream memStream = new MemoryStream();
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Serialize(memStream, inkPicture1.Image);
                    imgArray = memStream.GetBuffer();
                    string strImg = Convert.ToBase64String(imgArray);

                    this.richTextBox1.Text += "!imgdata" + strImg + "\n";
                    vapi.sndMessage("!imgdata" + strImg);

                }

                this.inkPicture1.Invalidate();
            }


        }

        //background color
        private void ribbonButton18_Click(object sender, EventArgs e)
        {
            ColorDialog colorDlg = new ColorDialog();
            colorDlg.AllowFullOpen = true;
            colorDlg.AnyColor = true;
            colorDlg.SolidColorOnly = false;
            colorDlg.Color = Color.Red;

            if (colorDlg.ShowDialog() == DialogResult.OK)
            {
                this.inkPicture1.BackColor = colorDlg.Color;
                this.inkPicture1.Image = null;

                if (inkPicture1.Ink.ExtendedProperties.Contains(guidImage))
                    inkPicture1.Ink.ExtendedProperties.Remove(guidImage);


                if ((inkPicture1.BackColor == Color.White) && (inkPicture1.Ink.ExtendedProperties.Contains(guidBGColor)))
                    inkPicture1.Ink.ExtendedProperties.Remove(guidBGColor);

            }

            //snd message
            //close image
            
            //snd bgcolor
            if (vapi != null)
            {
                byte[] bytes = null;

                //save ink and image
                MemoryStream memStream = new MemoryStream();

                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(memStream, inkPicture1.BackColor);

                bytes = memStream.GetBuffer();

                string strImg = Convert.ToBase64String(bytes);
                this.richTextBox1.Text += "!bgdata" + strImg + "\n";
                vapi.sndMessage("!bgdata" + strImg);
            }



        }

        //zoom in
        private void ribbonButton20_Click(object sender, EventArgs e)
        {
            if (this.inkPictureZoomFactor >= 8.0f)
                return;

            if (this.inkPictureZoomFactor > 1.0f)
            {
                float fTmp =((inkPictureZoomFactor + 1.0f) / inkPictureZoomFactor);
                this.inkPicture1.Renderer.Scale(fTmp, fTmp);
                this.inkPictureZoomFactor += 1.0f;
                
            }
            else
            {
                float fTmp = ((inkPictureZoomFactor *2.0f) / inkPictureZoomFactor);
                this.inkPicture1.Renderer.Scale(fTmp, fTmp);
                this.inkPictureZoomFactor *= 2.0f;
            }

            

            float fWidth = (float)this.inkPictureOriginHeightSz * this.inkPictureZoomFactor;
            this.inkPictureHeightSz = (int)fWidth;

            float fHeight = (float)this.inkPictureOriginWidthSz * inkPictureZoomFactor;
            this.inkPictureWidthSz = (int)fHeight;

            this.resetSz(this, null);

            //this.inkPicture1.Renderer.Scale(2.0f, 2.0f);

            //this.inkPictureHeightSz *= 2;
            //this.inkPictureWidthSz *= 2;

            //this.resetSz(this, null);



        }

        //zoom out
        private void ribbonButton21_Click(object sender, EventArgs e)
        {
            if (this.inkPictureZoomFactor <= 0.25f)
                return;

            if (this.inkPictureZoomFactor > 1.0f)
            {
                float fTmp = ((inkPictureZoomFactor - 1.0f) / inkPictureZoomFactor);
                this.inkPicture1.Renderer.Scale(fTmp, fTmp);
                this.inkPictureZoomFactor -= 1.0f;
            }
            else
            {
                float fTmp = ((inkPictureZoomFactor *0.5f) / inkPictureZoomFactor);
                this.inkPicture1.Renderer.Scale(fTmp, fTmp);
                this.inkPictureZoomFactor *= 0.5f;
            }

            //this.inkPicture1.Renderer.Scale(inkPictureZoomFactor, inkPictureZoomFactor);

            float fWidth = (float)this.inkPictureOriginHeightSz * this.inkPictureZoomFactor;
            this.inkPictureHeightSz = (int)fWidth;

            float fHeight = (float)this.inkPictureOriginWidthSz * inkPictureZoomFactor;
            this.inkPictureWidthSz = (int)fHeight;

            this.resetSz(this, null);

        }

        //100%
        private void ribbonButton22_Click(object sender, EventArgs e)
        {
            float fTmp = ((1.0f) / inkPictureZoomFactor);
            this.inkPicture1.Renderer.Scale(fTmp, fTmp);
            inkPictureZoomFactor = 1.0f;

            //this.inkPicture1.Renderer.Scale(1.0f, 1.0f);
            this.inkPictureHeightSz = this.inkPictureOriginHeightSz;
            this.inkPictureWidthSz = this.inkPictureOriginWidthSz;

            this.resetSz(this, null);

        }

        //save as...
        private void ribbonButton25_Click(object sender, EventArgs e)
        {
            SaveFileDialog savedlg = new SaveFileDialog();
            savedlg.Filter = "ISF files (*.isf)|*.isf| All files (*.*)|*.*";

            if (savedlg.ShowDialog() == DialogResult.OK)
            {
                Stream stream = savedlg.OpenFile();
                
                if (stream !=null && stream.Length >0)
                stream.Seek(0, 0);

                if (stream != null)
                {
                    byte[] bytes;

                    if (inkPicture1.Image != null)
                    {
                        //save ink and image
                        MemoryStream memStream = new MemoryStream();

                        BinaryFormatter bf = new BinaryFormatter();
                        bf.Serialize(memStream, inkPicture1.Image);

                        bytes = memStream.GetBuffer();
                        inkPicture1.Ink.ExtendedProperties.Add(guidImage, bytes);
                    }

                    if (inkPicture1.BackColor != Color.White)
                    {
                        //save ink and image
                        MemoryStream memStream = new MemoryStream();

                        BinaryFormatter bf = new BinaryFormatter();
                        bf.Serialize(memStream, inkPicture1.BackColor);

                        bytes = memStream.GetBuffer();
                        inkPicture1.Ink.ExtendedProperties.Add(guidBGColor, bytes);
                    }

                    bytes = inkPicture1.Ink.Save();
                    stream.Write(bytes, 0, bytes.Length);

                    //刪除 image guid 設定
                    if (inkPicture1.Image !=null)
                        inkPicture1.Ink.ExtendedProperties.Remove(guidImage);

                    if (inkPicture1.BackColor != Color.White)
                        inkPicture1.Ink.ExtendedProperties.Remove(guidBGColor);

                }
                stream.Close();
            }
        }

        //open file
        private void ribbonButton24_Click(object sender, EventArgs e)
        {
            OpenFileDialog opendlg = new OpenFileDialog();
            opendlg.Filter = "ISF files (*.isf)|*.isf| All files (*.*)|*.*";

            if (opendlg.ShowDialog() == DialogResult.OK)
            {
                Stream stream = opendlg.OpenFile();
                if (stream != null && stream.Length > 0)
                {
                    byte[] bytes = new byte[stream.Length];
                    if (stream.Read(bytes, 0, bytes.Length) == stream.Length)
                    {
                        Microsoft.Ink.Ink ink = new Microsoft.Ink.Ink();
                        ink.Load(bytes);

                        inkPicture1.InkEnabled = false;
                        inkPicture1.Ink = ink;
                        inkPicture1.InkEnabled = true;

                        inkPicture1.Image = null;
                        inkPicture1.BackColor = Color.White;

                        //load image
                        if (ink.ExtendedProperties.Contains(guidImage))
                        {
                            byte[] pb = (byte[])ink.ExtendedProperties[guidImage].Data;
                            System.IO.MemoryStream ms = new System.IO.MemoryStream(pb);
                            BinaryFormatter formatter = new BinaryFormatter();

                            inkPicture1.Image = (Image)formatter.Deserialize(ms);
                            inkPicture1.SizeMode = PictureBoxSizeMode.StretchImage;
                        }

                        //load bgcolor
                        if (ink.ExtendedProperties.Contains(guidBGColor))
                        {
                            byte[] pb = (byte[])ink.ExtendedProperties[guidBGColor].Data;
                            System.IO.MemoryStream ms = new System.IO.MemoryStream(pb);
                            BinaryFormatter formatter = new BinaryFormatter();
                            inkPicture1.BackColor = (Color)formatter.Deserialize(ms);
                        }

                        inkPicture1.Invalidate();

                    }
                    stream.Close();
                }
            }
        }

        //newink
        private void ribbonButton23_Click(object sender, EventArgs e)
        {
            //new inkpicture
            this.inkPicture1.InkEnabled = false;
            this.inkPicture1.Ink.DeleteStrokes();
            this.inkPicture1.InkEnabled = true;

            this.inkPicture1.Image = null;
            this.inkPicture1.BackColor = Color.White;

            if (inkPicture1.Ink.ExtendedProperties.Contains(guidImage))
                inkPicture1.Ink.ExtendedProperties.Remove(guidImage);

            if ((inkPicture1.BackColor == Color.White) && (inkPicture1.Ink.ExtendedProperties.Contains(guidBGColor)))
                inkPicture1.Ink.ExtendedProperties.Remove(guidBGColor);

            this.inkPictureHeightSz = this.inkPictureOriginHeightSz;
            this.inkPictureWidthSz = this.inkPictureOriginWidthSz;
            this.inkPictureZoomFactor = 1.0f;

            this.resetSz(this, null);

            this.inkPicture1.Invalidate();
            
        }

        private void ribbonButton9_Click(object sender, EventArgs e)
        {
            Form1 fm1 = new Form1();
            int num =fm1.getButtonClicked();

            switch (num)
            {
                case 0:
                    //fit screen
                    this.inkPictureOriginHeightSz = this.ClientSize.Height - this.ribbonControl1.ClientSize.Height;
                    this.inkPictureOriginWidthSz = this.ClientSize.Width;
                    //this.resetSz(this, null);

                    break;

                case 1:
                    //800x600
                    this.inkPictureOriginHeightSz = 600;
                    this.inkPictureOriginWidthSz = 800;
                    //resetSz(this, null);
                    break;

                case 2:
                    //1024x768
                    this.inkPictureOriginHeightSz = 768;
                    this.inkPictureOriginWidthSz = 1024;
                    //resetSz(this, null);
                    break;

                case 3:
                    //1152x864
                    this.inkPictureOriginHeightSz = 864;
                    this.inkPictureOriginWidthSz = 1152;
                    //resetSz(this, null);
                    break;
            }

            //100%
            ribbonButton22_Click(this, null);


        }

        //debug message
        private void ribbonButton17_Click(object sender, EventArgs e)
        {
            bDispDebugMessage = !bDispDebugMessage;

            if (bDispDebugMessage)
                this.ribbonButton17.IsPressed = true;
            else
                this.ribbonButton17.IsPressed = false;

            this.resetSz(this, null);
        }


        public void networkSwitch()
        {
            this.ribbonButton13_Click(null, null);
        }

        //listen
        private ink.Network.vastAPI vapi = null;
        //private static OpenServe.Client.ClientModule client = null;
        public void ribbonButton13_Click(object sender, EventArgs e)
        {
            this.inkPicture1.InkEnabled = false;
            bListen = !bListen;

            if (bListen)
            {
                //openserve.net---------------------------------------
                //////begin listen
                ////client =new OpenServe.Client.ClientModule();
                ////IPAddress serveradd =IPAddress.Parse("127.0.0.1");
                ////IPEndPoint ep =new IPEndPoint(serveradd, 5000);
                ////client.OnDataReceived += new OpenServe.Client.StringDelegate(client_OnDataReceived);
                //////client.OnConnectionTimeOut += new OpenServe.Client.StringDelegate(client_OnConnectionTimeOut);
                ////client.ConnectTimeout =1000; //1sec ?
                ////client.Connect(ep);

                ////if (client.isConnected)
                ////{
                ////    this.richTextBox1.Text += "Connection Successful.\n";
                ////    //disable connect button
                ////    this.ribbonButton16.Enabled = false; //configure
                ////    this.ribbonButton13.IsPressed = true;

                ////}
                ////else
                ////{
                ////    this.richTextBox1.Text += "Connection Failed.\n";
                ////    bListen = false;
                ////}

                //vast------------------------------------------------
                vapi = new ink.Network.vastAPI();
                vapi.OnDataReceived += new Network.StringDelegate(vapi_OnDataReceived);
                //if (vapi.startVAST("127.0.0.1", "1037", false) == true)
                if (vapi.startVAST("140.109.22.70", "37", false) == true)
                {
                    this.richTextBox1.Text += "Connection Successful.\n";
                    //disable connect button
                    this.ribbonButton16.Enabled = false; //configure
                    this.ribbonButton13.IsPressed = true;
                }
                else
                {
                    this.richTextBox1.Text += "Connection Failed.\n";
                    bListen = false;
                }
                //----------------------------------------------------


            }
            else
            {
                //openserve.net---------------------------------------
                //////stop listen
                ////client.Disconnect();
                ////client.Shutdown();

                ////client = null;

                //vast------------------------------------------------
                vapi.releaseVAST();
                vapi = null;

                System.Threading.Thread.Sleep(2000);

                //----------------------------------------------------

                this.richTextBox1.Text += "disconnection successful.\n";
                //enable connect button
                this.ribbonButton16.Enabled = true; //configure
                this.ribbonButton13.IsPressed = false;


            }

            this.inkPicture1.InkEnabled = true;
        }

        
        delegate void SetVASTTextCallback(object sender, ulong from, string text);
        void vapi_OnDataReceived(object sender, ulong from, string data)
        {
            if (this.richTextBox1.InvokeRequired)
            {
                SetVASTTextCallback d = new SetVASTTextCallback(vapi_OnDataReceived);
                this.Invoke(d, new object[] { sender, from, data });

            }
            else
            {
                this.richTextBox1.Text += "Recieving...\n";
                this.richTextBox1.Text += data;
                this.richTextBox1.Text += "\n";

                //rcv data
                if (data.Length > 5 && data.Substring(0, 5) == "!data")
                {
                    string strInkData = data.Substring(5);
                    byte[] byteArray = Convert.FromBase64String(strInkData);

                    this.inkPicture1.InkEnabled = false;
                    inkPicture1.Ink = new Microsoft.Ink.Ink();
                    inkPicture1.Ink.InkAdded += new Microsoft.Ink.StrokesEventHandler(Strokes_StrokesAdded);
                    inkPicture1.Ink.InkDeleted += new Microsoft.Ink.StrokesEventHandler(Strokes_StrokesRemoved);

                    this.inkPicture1.Ink.Load(byteArray);

                    this.inkPicture1.InkEnabled = true;

                    this.inkPicture1.Invalidate();
                }

                if (data.Length > 8 && data.Substring(0, 8) == "!imgdata")
                {
                    string strImg = data.Substring(8);
                    byte[] byteArray = Convert.FromBase64String(strImg);

                    byte[] pb = (byte[])byteArray;
                    System.IO.MemoryStream ms = new System.IO.MemoryStream(pb);
                    BinaryFormatter formatter = new BinaryFormatter();

                    inkPicture1.Image = (Image)formatter.Deserialize(ms);
                    inkPicture1.SizeMode = PictureBoxSizeMode.StretchImage;

                    this.inkPicture1.Invalidate();

                }

                if (data.Length > 7 && data.Substring(0, 7) == "!bgdata")
                {
                    string strImg = data.Substring(7);
                    byte[] byteArray = Convert.FromBase64String(strImg);

                    System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray);
                    BinaryFormatter formatter = new BinaryFormatter();
                    inkPicture1.BackColor = (Color)formatter.Deserialize(ms);
                    inkPicture1.Image = null;

                    if (inkPicture1.Ink.ExtendedProperties.Contains(guidImage))
                        inkPicture1.Ink.ExtendedProperties.Remove(guidImage);

                    if ((inkPicture1.BackColor == Color.White) && (inkPicture1.Ink.ExtendedProperties.Contains(guidBGColor)))
                        inkPicture1.Ink.ExtendedProperties.Remove(guidBGColor);


                    this.inkPicture1.Invalidate();

                }

            }

            //throw new NotImplementedException();
        }

        //delegate void SetTextCallback(object sender, string text);
        //void client_OnDataReceived(object sender, string data)
        //{
        //    if (this.richTextBox1.InvokeRequired)
        //    {
        //        SetTextCallback d = new SetTextCallback(client_OnDataReceived);
        //        this.Invoke(d, new object[] { sender, data });

        //    }
        //    else
        //    {
        //        this.richTextBox1.Text += "Recieving...\n";
        //        this.richTextBox1.Text += data;
        //        this.richTextBox1.Text += "\n";
                
        //        //rcv data
        //        if (data.Length > 5 && data.Substring(0, 5) == "!data")
        //        {
        //            string strInkData = data.Substring(5);
        //            byte[] byteArray = Convert.FromBase64String(strInkData);

        //            this.inkPicture1.InkEnabled = false;
        //            inkPicture1.Ink = new Microsoft.Ink.Ink();
        //            inkPicture1.Ink.InkAdded +=new Microsoft.Ink.StrokesEventHandler(Strokes_StrokesAdded);
        //            inkPicture1.Ink.InkDeleted +=new Microsoft.Ink.StrokesEventHandler(Strokes_StrokesRemoved);

        //            this.inkPicture1.Ink.Load(byteArray);

        //            this.inkPicture1.InkEnabled = true;

        //            this.inkPicture1.Invalidate();
        //        }

        //        if (data.Length > 8 && data.Substring(0, 8) == "!imgdata")
        //        {
        //            string strImg = data.Substring(8);
        //            byte[] byteArray = Convert.FromBase64String(strImg);

        //            byte[] pb = (byte[])byteArray;
        //            System.IO.MemoryStream ms = new System.IO.MemoryStream(pb);
        //            BinaryFormatter formatter = new BinaryFormatter();

        //            inkPicture1.Image = (Image)formatter.Deserialize(ms);
        //            inkPicture1.SizeMode = PictureBoxSizeMode.StretchImage;

        //            this.inkPicture1.Invalidate();

        //        }

        //    }

        //}

        void Strokes_StrokesRemoved(object sender, Microsoft.Ink.StrokesEventArgs e)
        {
            
            //throw new NotImplementedException();
        }

        void Strokes_StrokesAdded(object sender, Microsoft.Ink.StrokesEventArgs e)
        {
            //if (client != null)
            //{
            //    byte[] byteArray = this.inkPicture1.Ink.Save(/*Microsoft.Ink.PersistenceFormat.Gif*/);
            //    string str = Convert.ToBase64String(byteArray);

            //    client.Send("!ANNOUNCE " + "!data" + str);
            //}

            if (vapi != null)
            {
                byte[] byteArray = this.inkPicture1.Ink.Save(/*Microsoft.Ink.PersistenceFormat.Gif*/);
                string str = Convert.ToBase64String(byteArray);

                this.richTextBox1.Text += "!data" + str + "\n";
                vapi.sndMessage("!data" + str);
            }

                
            //throw new NotImplementedException();
        }







        





    }
}
